package com.k.kpp.web.easyexcel.downtemplate;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Map;

/**
 * @author ljw
 */
public class ExcelDropDownHandler implements SheetWriteHandler {

    /**
     * 下拉框值
     */
    private Map<Integer,String[]> dropDownMap;


    /**
     * 开始行
     */
    private Integer firstRow = 1;

    /**
     * 结束行
     */
    private Integer lastRow = 65534;

    public ExcelDropDownHandler(Map<Integer,String[]> dropDownMap) {
        this.dropDownMap = dropDownMap;
    }

    public ExcelDropDownHandler(Map<Integer, String[]> dropDownMap, Integer firstRow, Integer lastRow) {
        this.dropDownMap = dropDownMap;
        this.firstRow = firstRow;
        this.lastRow = lastRow;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();
        dropDownMap.forEach((celIndex, values) -> {
            CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(firstRow, lastRow, celIndex, celIndex);
            DataValidationConstraint constraint = helper.createExplicitListConstraint(values);
            DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);

            // 限制输入校验
            dataValidation.setErrorStyle(0);
            dataValidation.setShowErrorBox(true);
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.createErrorBox("提示", "请输入下拉选项中的内容");

            sheet.addValidationData(dataValidation);
        });
    }
}
